//
//  NSString+LBAddition.m
//  LBFoundation
//
//  Created by WuShiHai on 19/5/24.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "NSString+LBAddition.h"
#import <CommonCrypto/CommonHMAC.h>

@implementation NSString (LBAddition)

- (BOOL)isPhone {
    NSString *regex = @"^(1[0-9])\\d{9}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:self];
}

- (NSString *)formatPhone {
    if (self.length <= 3) {
        return self;
    }
    
    NSInteger leftLength = self.length - 3;
    NSInteger index = leftLength / 4;
    if (leftLength % 4 == 0) {
        index--;
    }
    NSMutableString *whiteSpceText = [self mutableCopy];
    [whiteSpceText insertString:@" " atIndex:3];
    for(int i = 1 ; i <= index ; i++){
        [whiteSpceText insertString:@" " atIndex: 4 + i * 5 - 1];
    }
    return whiteSpceText;
}

- (NSString *)trimAllSpace {
    return [self stringByReplacingOccurrencesOfString:@" " withString:@""];
}

- (NSString *)replaceEmojiWithString:(NSString *)replaceString {
    
    NSString *emojiPattern1 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900-\\U0001F9FF]"; //Code Points with default emoji representation
    NSString *emojiPattern2 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900–\\U0001F9FF]\\uFE0F"; //Characters with emoji variation selector
    NSString *emojiPattern3 = @"[\\u2600-\\u27BF\\U0001F300-\\U0001F77F\\U0001F900–\\U0001F9FF][\\U0001F3FB-\\U0001F3FF]"; //Characters with emoji modifier
    NSString *emojiPattern4 = @"[\\U0001F1E6-\\U0001F1FF][\\U0001F1E6-\\U0001F1FF]"; //2-letter flags
    NSString *pattern = [NSString stringWithFormat:@"\(%@)|\(%@)|\(%@)|\(%@)", emojiPattern4, emojiPattern3, emojiPattern2, emojiPattern1];
    NSString *regex = [NSString stringWithFormat:@"(?:\(%@))(?:\\u200D(?:\(%@)))*", pattern, pattern];
    NSError *error = nil;
    NSRegularExpression *express = [NSRegularExpression regularExpressionWithPattern:regex options:0 error:&error];
    NSString *newString = [express stringByReplacingMatchesInString:self options:0 range:NSMakeRange(0, self.length) withTemplate:replaceString];
    return newString;
}

- (NSString *)lastPathComponentEscapingParamters {
    NSString *lastPathComponent = self.lastPathComponent;
    if (lastPathComponent.length > 0) {
        return [lastPathComponent componentsSeparatedByString:@"?"].firstObject;
    }
    return nil;
}

- (NSString *)URLEncode {
    NSCharacterSet *allowedCharacters = [NSCharacterSet URLFragmentAllowedCharacterSet];
    return [self stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
}

- (NSString *)URLDecode {
    NSURL *URL = [NSURL URLWithString:self];
    NSURLComponents *components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO];
    return components.string;
}

- (NSDictionary<NSString *, NSString *> *)queryItemsFromURLString {
    if ([self length] > 0) {
        NSArray<NSURLQueryItem *> *queryItems = [[[NSURLComponents alloc] initWithString:self] queryItems];
        NSMutableDictionary *queryKeyValues = [@{} mutableCopy];
        [queryItems enumerateObjectsUsingBlock:^(NSURLQueryItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.value && obj.name) {
                [queryKeyValues setObject:obj.value forKey:obj.name];
            }
        }];
        return [queryKeyValues copy];
    }
    return nil;
}

//md5加密
- (NSString*)MD5 {
    const char *cStr = [self UTF8String];
    unsigned char result[32];
    CC_MD5( cStr, (int)strlen(cStr),result );
    NSMutableString *hash =[NSMutableString string];
    for (int i = 0; i < 16; i++)
        [hash appendFormat:@"%02X", result[i]];
    return [hash uppercaseString];
}

- (NSString *)base64EncodedString {
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}

- (NSString *)base64DecodedString {
    NSData *data = [[NSData alloc]initWithBase64EncodedString:self options:0];
    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}

- (NSString *)removeFileSystem {
    return [[self stringByReplacingOccurrencesOfString:@"file:///" withString:@"/"] stringByReplacingOccurrencesOfString:@"file:/" withString:@"/"];
}

@end
